<script setup lang="ts">
import { onClickOutside, useDebounceFn, useToggle } from '@peng_kai/kit/libs/vueuse';

export type ProviderList = Api.GetData<typeof apis.apiGameTypeDetail>['provider'];

const props = defineProps<{ alias: string; supplier: string[] | number[] }>();
const emits = defineEmits<{
  change: [{ codes: string[]; checked: ProviderList[] }];
}>();
const target = ref(null);
const supplier = ref([]);
const search = ref('');
const [show, toggle] = useToggle(false);

const alias = toRef(props, 'alias');
const { list, storage } = useList();

// 添加防抖假装查询远程
const onSearch = useDebounceFn(() => {
  if (!search.value) {
    list.value = storage.value;
    return;
  }
  // 模糊查询
  list.value = list.value.filter(i => (i.name.toLowerCase()).includes(search.value?.toLowerCase()));
}, 100);

onClickOutside(target, event => (show.value = false));

function useList() {
  const { data, refetch } = useQuery({
    queryKey: ['apiGameTypeDetail', () => alias],
    queryFn: () => apis.apiGameTypeDetail({ alias: alias.value }),
  });
  const list = ref<ProviderList>([]);
  const storage = computed(() => (data?.value?.provider || []).map(i => ({ ...i, checked: false })));
  watch(alias, (newVal, oldVal) => {
    if (!!newVal && newVal !== oldVal) {
      console.log('list.value', newVal);
      list.value = [];
    }
  });
  watchEffect(() => {
    if (!data?.value?.provider)
      return;
    list.value = (data?.value?.provider || []).map(i => ({ ...i, checked: false }));
  });

  return {
    refetch,
    list,
    storage,
  };
}

function onChange(e: any[]) {
  // 更新 `list` 中对应项的 `checked` 状态
  const checked: any[] = [];
  list.value.forEach((item: any) => {
    item.checked = e.includes(item.provider_code);
    if (item.checked) {
      checked.push(item);
    }
  });
  list.value.sort((a, b) => b.checked - a.checked);

  emits('change', { codes: e, checked });
}
</script>

<template>
  <div ref="target" class="relative">
    <div class="mb-1 max-w-240px min-w-180px flex-between rounded-lg bg-sys-layer-a px-4 py-2" @click="toggle()">
      <div>
        {{ $t('ddIuKiX1vvg6eVhkbhXnR') }} <span v-if="supplier.length > 0" class="text-12px">{{ supplier.length ?? 0 }}</span>
      </div>
      <i class="i-ion:ios-arrow-down rotate--90" />
    </div>
    <div v-if="show" ref="target" class="absolute z-2 rounded-lg bg-sys-layer-a !px-0 !py-2 !shadow-none">
      <div class="mb-2 px-3 text-sys-text-body">
        <TAntdTheme component="Input" theme="light">
          <AInput
            v-model:value="search"
            class="text-sm"
            allowClear
            :placeholder="$t('yaumayCeCeamLBiC9G8Dn')"
            size="small"
            :bordered="true"
            @input="onSearch()"
          >
            <template #prefix>
              <i class="i-local:search text-sys-text-body" />
            </template>
          </AInput>
        </TAntdTheme>
      </div>
      <ACheckboxGroup
        v-model:value="supplier"
        shape="square"
        checkedColor="#B91B1B"
        iconSize="14px"
        class="w-full"
        @change="onChange"
      >
        <ul class="max-h-80 w-full overflow-y-auto px-1.5 text-left">
          <li v-for="(i, k) in list" :key="k" :class="supplier.includes(i.provider_code) ? 'bg-sys-layer-d rounded-md ' : ''" class="mb-1 list-none px-2 py-2">
            <ACheckbox :value="i.provider_code">
              <span class="text-sys-text-body" :class="supplier.includes(i.provider_code) ? 'text-sys-text-head ' : ''">{{ i.name }}</span>
            </ACheckbox>
          </li>
        </ul>
      </ACheckboxGroup>
    </div>
  </div>
</template>
